<template>
  <wd-popup v-model="visible" :show-close-icon="true" position="center" round>
    <view class="popup-wrapper">
      <!-- ✅ 点击图片刷新验证码 -->
      <image class="captcha-img" :src="captchaUrl" mode="widthFix" @click="handleRefreshCaptcha" />
      <wd-input
        v-model="captchaInput"
        placeholder="请输入图中字符"
        clearable
        class="captcha-input"
      />
      <view v-if="captchaError" class="text-red text-sm mt-2">{{ captchaError }}</view>
      <view class="flex justify-center mt-4">
        <wd-button type="error" size="large" @click="onConfirm">确定</wd-button>
      </view>
    </view>
  </wd-popup>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { getCode } from '@/api/login'

const visible = ref(false)
const captchaUrl = ref('')
const uuid = ref('')
const captchaInput = ref('')

const emit = defineEmits<{
  (e: 'success', payload: { code: string; uuid: string }): void
}>()
const captchaError = ref('')
/** 弹出弹窗并自动加载验证码 */
const open = async (imgUrl, uuId) => {
  visible.value = true
  captchaInput.value = ''
  captchaError.value = ''
  captchaUrl.value = imgUrl
  uuid.value = uuId
  console.log('captchaUrl.value', captchaUrl.value)
  console.log('uuid.value', uuid.value)

  // await refreshCaptcha()
}

/** 关闭弹窗 */
const close = () => {
  visible.value = false
}

/** 确认按钮：传出验证码和uuid */
const onConfirm = () => {
  if (!captchaInput.value.trim()) {
    captchaError.value = '验证码不能为空'
    return
  }

  // 清空错误
  captchaError.value = ''
  visible.value = false
  console.log('code', captchaInput.value)
  console.log('uuid', uuid)

  emit('success', {
    code: captchaInput.value,
    uuid: uuid.value,
  })
}

/** 刷新验证码：点击图片时调用 */
const handleRefreshCaptcha = async () => {
  await refreshCaptcha()
}

/** 请求后端获取验证码图片和uuid */
const refreshCaptcha = async () => {
  try {
    const res = await getCode()
    captchaUrl.value = 'data:image/png;base64,' + res.data.img
    uuid.value = res.data.uuid
  } catch (err) {
    uni.showToast({ title: '获取验证码失败', icon: 'none' })
  }
}

defineExpose({ open, close })
</script>

<style scoped>
.popup-wrapper {
  padding: 40rpx;
  width: 80vw;
  border-radius: 20rpx;
  background-color: #fff;
}

.captcha-img {
  width: 100%;
  height: auto;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.captcha-input {
  border: 1px solid #ccc;
  border-radius: 12rpx;
  padding: 10rpx;
}
</style>
